package com.itheima.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dubbo.utils.IdWorker;
import com.itheima.dubbo.utils.TimeLineSave;
import com.itheima.model.mongo.Friend;
import com.itheima.model.mongo.Movement;
import com.itheima.model.mongo.MovementTimeLine;
import com.itheima.model.vo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private TimeLineSave timeLineSave;

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created"))));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pageResult = new PageResult();
        pageResult.setItems(movements);
        return pageResult;
    }

    @Override
    public void publish(Movement movement) {
        try {
            //保存自己的动态
            movement.setPid( idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            //movement.setId(ObjectId.get());//手动设置自动生成id，不写可以让mogo自动生成
            mongoTemplate.save(movement);
            //异步调用保存动态时间线表
            timeLineSave.saveMovementTimeLine(movement.getId(),movement.getUserId());
            /*//查询好友
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            //动态时间线
            List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId",Long.class);
            for (Long friendId : friendIds) {
                MovementTimeLine movementTimeLine = new MovementTimeLine();
                movementTimeLine.setMovementId(id);
                movementTimeLine.setUserId(userId);
                movementTimeLine.setFriendId(friendId);
                movementTimeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.save(movementTimeLine);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            //这里需要事务处理（mongodb处理事务能力弱需要手动处理）
        }
    }
/*查询用户的好友发布的信息*/
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //先查询动态时间表查询好友的id
        Query query = Query.query(Criteria.where("friendId").is(friendId)).with(PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created"))));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //根据动态的id查询好友动态
        Query query1 = Query.query(Criteria.where("id").in(movementIds));
        List<Movement> movements = mongoTemplate.find(query1, Movement.class);
        return movements;

    }
    /*随机生成条pagesize数据*/
    @Override
    public List<Movement> randomMovements(Integer pagesize) {
       TypedAggregation aggregation= Aggregation.newAggregation(Movement.class,Aggregation.sample(pagesize));//随机生成pagesize条Movement的数据
        AggregationResults<Movement> res = mongoTemplate.aggregate(aggregation, Movement.class);
        return res.getMappedResults();
    }
    /*根据pids查询movements*/
    @Override
    public List<Movement> findMovementsBypids(List<Long> pids) {
        return mongoTemplate.find(Query.query(Criteria.where("pid").in(pids)),Movement.class);
    }
    //根据id查询动态
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("pid").is(Long.valueOf(movementId))),Movement.class);
    }




    //设置通过动态
    @Override
    public Map<String, String> pass(ArrayList<Long> objectIds) {

        //设置动态的sta字段为通过的3
        Update update = new Update();
        update.set("state", 5);
        Query query = Query.query(Criteria.where("pid").in(objectIds).and("state").is(3));
        int count = (int) mongoTemplate.count(query, Movement.class);
        if (count != objectIds.size()) {
            //说明传入的并不全是待审核状态报错 返回null
            return null;
        }
        mongoTemplate.updateFirst(query, update, Movement.class);
        //防止乱选 判断传入的参数对应的字段必须为待审核
        //构造返回
        Map<String, String> map = new HashMap<>();
        map.put("message", "adipisicing pariatur Ut");
        return map;

    }

    //设置拒绝动态
    @Override
    public Map<String, String> reject(ArrayList<Long> objectIds) {
        //设置动态的sta字段为拒绝4
        Update update = new Update();
        update.set("state", 4);
        Query query = Query.query(Criteria.where("pid").in(objectIds).and("state").is(3));
        int count = (int) mongoTemplate.count(query, Movement.class);
        if (count != objectIds.size()) {
            //说明传入的并不全是待审核状态报错 返回null
            return null;
        }
        mongoTemplate.updateFirst(query, update, Movement.class);
        //构造返回
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }

    //设置撤销状态
    @Override
    public Map<String, String> revocation(ArrayList<Long> objectIds) {
        //设置动态的sta字段撤销状态为 2
        Update update = new Update();
        update.set("state", 3);
        Query query = Query.query(Criteria.where("pid").in(objectIds).and("state").in(4,5));
        Movement one = mongoTemplate.findOne(query, Movement.class);
        mongoTemplate.updateFirst(query, update, Movement.class);
        //构造返回
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }

    @Override
    public Long count(ArrayList<Integer> ids) {
        //根据ids 获得不同状态的数量
        long sstate = mongoTemplate.count(Query.query(Criteria.where("state").in(ids)), Movement.class);
        return sstate;
    }

    @Override
    public List<Movement> getmassage(int page, int pagesize, String sortProp, String sortOrder, String id, Long sd, Long ed, Integer state,Long uid) {



        //根据判断条件筛选列表
        Query query = new Query();
        if (sd != null && ed != null) {
            if (sd != -1L) {
                Criteria criteria = Criteria.where("created").gte(sd).lte(ed);
                query.addCriteria(criteria);
            }

        }
        if (id != null && StringUtils.isNotEmpty(id)) {
            Criteria criteria_a = Criteria.where("userId").is(id);
            query.addCriteria(criteria_a);
        }
        if (uid != null) {
            Criteria criteria_b = Criteria.where("userId").is(uid);
            query.addCriteria(criteria_b);
        }


        if (state != null) {
            if (state == 1){
                Criteria criteria_c = Criteria.where("state").in(1,2,3,4,5);
                query.addCriteria(criteria_c);
            }else if (state == 2){
                Criteria criteria_c = Criteria.where("state").is(3);
                query.addCriteria(criteria_c);
            }else if (state == 3){
                Criteria criteria_c = Criteria.where("state").is(5);
                query.addCriteria(criteria_c);
            }else {
                Criteria criteria_c = Criteria.where("state").is(state);
                query.addCriteria(criteria_c);
            }




        }

        if (sortProp != null && sortOrder != null) {
            //这是排序字段和排序方式 两个都要不为null
            if ("ascending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.asc(sortProp)));

            } else if ("descending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.desc(sortProp)));
            }

        }

        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;


    }

    @Override
    public List<Movement> getlist(int page, int pagesize, String sortProp, String sortOrder, Long uid) {

        IPage pageinfo = new Page(page,pagesize);


        Query query = Query.query(Criteria.where("userId").is(uid)).skip((page - 1) * pagesize ).limit(pagesize);

        if (sortProp != null && sortOrder != null) {
            //这是排序字段和排序方式 两个都要不为null
            if ("ascending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.asc(sortProp)));

            } else if ("descending".equals(sortOrder)) {
                query.with(Sort.by(Sort.Order.desc(sortProp)));
            }

        }
        List<Movement> movements = mongoTemplate.find(query, Movement.class);


        return movements;
    }


}
